#include "Oriented3DBox.h"

Oriented3DBox::Oriented3DBox()
{
	m_Axes[0] = Vec3f(1, 0, 0);
	m_Axes[1] = Vec3f(0, 1, 0);
	m_Axes[2] = Vec3f(0, 0, 1);
	m_Centre = Vec3f();
}

void Oriented3DBox::GetCorners(Vec3f Corners[8])
{
	Corners[0] = m_Centre +
		m_Axes[0] * m_Distances[0] +
		m_Axes[1] * m_Distances[1] +
		m_Axes[2] * m_Distances[2];

	Corners[1] = m_Centre +
		m_Axes[0] * m_Distances[0] +
		m_Axes[1] * m_Distances[1] -
		m_Axes[2] * m_Distances[2];

	Corners[2] = m_Centre +
		m_Axes[0] * m_Distances[0] -
		m_Axes[1] * m_Distances[1] -
		m_Axes[2] * m_Distances[2];

	Corners[3] = m_Centre -
		m_Axes[0] * m_Distances[0] -
		m_Axes[1] * m_Distances[1] -
		m_Axes[2] * m_Distances[2];

	Corners[4] = m_Centre -
		m_Axes[0] * m_Distances[0] +
		m_Axes[1] * m_Distances[1] +
		m_Axes[2] * m_Distances[2];

	Corners[5] = m_Centre -
		m_Axes[0] * m_Distances[0] -
		m_Axes[1] * m_Distances[1] +
		m_Axes[2] * m_Distances[2];

	Corners[6] = m_Centre +
		m_Axes[0] * m_Distances[0] -
		m_Axes[1] * m_Distances[1] +
		m_Axes[2] * m_Distances[2];

	Corners[7] = m_Centre -
		m_Axes[0] * m_Distances[0] +
		m_Axes[1] * m_Distances[1] -
		m_Axes[2] * m_Distances[2];
}


bool Oriented3DBox::isIntersecting(Oriented3DBox other)
{
	//get all 15 axies
	Vec3f axes[15] = 
	{
		m_Axes[0],
		m_Axes[1],
		m_Axes[2],
		other.m_Axes[0],
		other.m_Axes[1],
		other.m_Axes[2],
		CrossProduct(m_Axes[0], other.m_Axes[0]),
		CrossProduct(m_Axes[0], other.m_Axes[1]),
		CrossProduct(m_Axes[0], other.m_Axes[2]),
		CrossProduct(m_Axes[1], other.m_Axes[0]),
		CrossProduct(m_Axes[1], other.m_Axes[1]),
		CrossProduct(m_Axes[1], other.m_Axes[2]),
		CrossProduct(m_Axes[2], other.m_Axes[0]),
		CrossProduct(m_Axes[2], other.m_Axes[1]),
		CrossProduct(m_Axes[2], other.m_Axes[2])
	};

	//get the corners for both boxes
	Vec3f box1Corners[8];
	GetCorners(box1Corners);

	Vec3f box2Corners[8];
	other.GetCorners(box2Corners);

	//foreach axis
	for(int axis = 0; axis < 15; axis++)
	{
		float min1= 0;
		float max1 = 0;
		float min2 = 0;
		float max2 = 0;
		for(int corner = 0; corner < 8; corner++)
		{
			//take a cornder of box 1 and project it onto the
			//current axis, then a corner of box 2
			//this gives a float for each corner
			float projectedcornerforbox1 = 
				DotProduct(box1Corners[corner], axes[axis]);

			if(projectedcornerforbox1 > max1)
			{
				max1 = projectedcornerforbox1;
			}
			if(projectedcornerforbox1 < min1)
			{
				min1 = projectedcornerforbox1;
			}

			float projectedcornerforbox2 =
				DotProduct(box2Corners[corner], axes[axis]);

			if(projectedcornerforbox2 > max2)
			{
				max2 = projectedcornerforbox2;
			}
			if(projectedcornerforbox2 < min2)
			{
				min2 = projectedcornerforbox2;
			}

		}
			// are they seperate? if so return false
			if(!min1 < max2 && min2 < max1)
			{
				return false;
			}
	}

	return true;
}